package dk.mitaffald.main;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import dk.tankegang.mitaffald.R;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.Vibrator;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class LocationBased extends ListActivity{

	// JSON Node names
    private static final String TAG_Location = "location_id";
    private static final String TAG_Company = "company_id";
    private static final String TAG_NAME = "name";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_PLACE = "place";
    private static final String TAG_POSTAL = "postal";
    private static final String TAG_CITY = "city";
    private static final String TAG_MONDAY = "monday";
    private static final String TAG_TUESDAY = "tuesday";
    private static final String TAG_WEDNESDAY = "wednesday";
    private static final String TAG_THURSDAY = "thursday";
    private static final String TAG_FRIDAY = "friday";
    private static final String TAG_SATURDAY = "saturday";
    private static final String TAG_SUNDAY = "sunday";
    private static final String TAG_TYPE = "type";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";
    private static final String TAG_NOCAR = "nocar";
    private static final String TAG = "Debug of Project"; // 
	
    private String a;
	private String b;
	
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		
       // myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

		
		SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
        
        String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
        Cursor cursor = db.rawQuery(query, null);
        if(cursor != null)
        {
        cursor.moveToFirst();
         a = cursor.getString(0);
         b = cursor.getString(1);
        }
 
        
       String url = "http://webservice.mitaffald.dk/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
 
	    Log.d(TAG, "Leyth URL = Lat : " + a +"     Long : " + b); 
	    
	    
		// now enabled if disabled = ingen support for jb aka 4.0
		 if (android.os.Build.VERSION.SDK_INT > 9) {
		      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		      StrictMode.setThreadPolicy(policy);
		 }
	
	    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
		JSONParser jParser = new JSONParser();
     	JSONArray json = jParser.getJSONFromUrl(url);
    	try {
			   for(int i = 0; i < json.length(); i++){
			        JSONObject c = json.getJSONObject(i);
		        
				String location_id = c.getString(TAG_Location);
				String company_id = c.getString(TAG_Company);
				String name = c.getString(TAG_NAME);
				String address = c.getString(TAG_ADDRESS);
				String place = c.getString(TAG_PLACE) ;	
				String postal = c.getString(TAG_POSTAL);
				String city = c.getString(TAG_CITY);
				
				String monday = c.getString(TAG_MONDAY);
				if(c.getString(TAG_MONDAY).isEmpty())
					{
						monday="Lukket";
					}
				else
					{
						monday=c.getString(TAG_MONDAY);
					}
				
				String tuesday = c.getString(TAG_TUESDAY);
				if(c.getString(TAG_TUESDAY).isEmpty())
					{
						tuesday="Lukket";
					}
				else
					{
						tuesday=c.getString(TAG_TUESDAY);
					}

				String wednesday = c.getString(TAG_WEDNESDAY);	
				if(c.getString(TAG_WEDNESDAY).isEmpty())
					{
						wednesday="Lukket";
					}
				else
					{
						wednesday=c.getString(TAG_WEDNESDAY);
					}
				
				String thursday = c.getString(TAG_THURSDAY);
				if(c.getString(TAG_THURSDAY).isEmpty())
					{
						thursday="Lukket";
					}
				else
					{
						thursday=c.getString(TAG_THURSDAY);
					}
					
				String friday = c.getString(TAG_FRIDAY);
				if(c.getString(TAG_FRIDAY).isEmpty())
					{
						friday="Lukket";
					}
				else
					{
						friday=c.getString(TAG_FRIDAY);
					}
					
				String saturday = c.getString(TAG_SATURDAY);
				if(c.getString(TAG_SATURDAY).isEmpty())
					{
						saturday="Lukket";
					}
				else
					{
						saturday=c.getString(TAG_SATURDAY);
					}	
				
				String sunday=c.getString(TAG_SUNDAY);
				if(c.getString(TAG_SUNDAY).isEmpty())
					{
						sunday="Lukket";
					}
				else
					{
						sunday=c.getString(TAG_SUNDAY);
					}
	
				

				String nocar = c.getString(TAG_NOCAR);
				String type = c.getString(TAG_TYPE);
				
				String lat = c.getString(TAG_LAT);
				String lng = c.getString(TAG_LNG);
				
			
				//Log.d(TAG, "Leyth Days = Testing : " + monday +"     Testing 2 : " + wednesday); 

				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();
				
				// adding each child node to HashMap key => value
				map.put(TAG_Location, location_id);
				map.put(TAG_Company, company_id);
				map.put(TAG_NAME, name);
				map.put(TAG_ADDRESS, address);
				map.put(TAG_PLACE, place);
				map.put(TAG_POSTAL, postal);
				map.put(TAG_CITY, city);
				map.put(TAG_MONDAY, monday);
				map.put(TAG_TUESDAY, tuesday);
				map.put(TAG_WEDNESDAY, wednesday);
				map.put(TAG_THURSDAY, thursday);
				map.put(TAG_FRIDAY, friday);
				map.put(TAG_SATURDAY, saturday);
				map.put(TAG_SUNDAY, sunday);
				map.put(TAG_TYPE, type);
				map.put(TAG_LAT, lat);
				map.put(TAG_LNG, lng);
				map.put(TAG_NOCAR, nocar);
				
				// adding HashList to ArrayList
				contactList.add(map);
			   }
		} catch (JSONException e) {
		    e.printStackTrace();
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			
		}


		/**
		 * Updating parsed JSON data into ListView
		 * */
	
    	ListAdapter adapter2 = new SimpleAdapter(this, contactList,
				R.layout.list_item,
				new String[] { TAG_NAME, TAG_ADDRESS, TAG_CITY, TAG_POSTAL, TAG_LAT, TAG_LNG,TAG_MONDAY,TAG_TUESDAY,TAG_WEDNESDAY,TAG_THURSDAY,TAG_FRIDAY,TAG_SATURDAY,TAG_SUNDAY}, new int[] {
    			R.id.name, R.id.adresse, R.id.by, R.id.email, R.id.lat, R.id.lng, R.id.textView1, R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5,R.id.textView6,R.id.textView7, });

    
    	
    	
    	setListAdapter(adapter2);

	 	// selecting single ListView item
		ListView lv = getListView();

		// Launching new screen on Selecting Single ListItem
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				
				// getting values from selected ListItem
				String navn = ((TextView) view.findViewById(R.id.name)).getText().toString();
				String adresse = ((TextView) view.findViewById(R.id.adresse)).getText().toString();		

				String by = ((TextView) view.findViewById(R.id.by)).getText().toString();
				String zip = ((TextView) view.findViewById(R.id.email)).getText().toString();		
				
				String name = ((TextView) view.findViewById(R.id.lat)).getText().toString();
				String cost = ((TextView) view.findViewById(R.id.lng)).getText().toString();		
				
				
	            String mandag = ((TextView)	 view.findViewById(R.id.textView1)).getText().toString();
	            String tirsdag = ((TextView) view.findViewById(R.id.textView2)).getText().toString();
	            String onsdag = ((TextView) view.findViewById(R.id.textView3)).getText().toString();
	            String torsdag = ((TextView) view.findViewById(R.id.textView4)).getText().toString();
	            String fredag = ((TextView) view.findViewById(R.id.textView5)).getText().toString();
	            String lordag = ((TextView) view.findViewById(R.id.textView6)).getText().toString();
	            String sondag = ((TextView) view.findViewById(R.id.textView7)).getText().toString();
	            
	   
	            // Starting new intent
		        Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
		          
	            
	            in.putExtra(TAG_NAME, navn);
	            in.putExtra(TAG_ADDRESS, adresse);
	            in.putExtra(TAG_CITY, by);
	            in.putExtra(TAG_POSTAL, zip);

	            in.putExtra(TAG_LAT, name);
	            in.putExtra(TAG_LNG, cost);

	            in.putExtra(TAG_MONDAY, mandag);
	            in.putExtra(TAG_TUESDAY, tirsdag);
	            in.putExtra(TAG_WEDNESDAY, onsdag);
	            in.putExtra(TAG_THURSDAY, torsdag);
	            in.putExtra(TAG_FRIDAY, fredag);
	            in.putExtra(TAG_SATURDAY, lordag);
	            in.putExtra(TAG_SUNDAY, sondag);
	            
			 //   Log.d(TAG, "Leyth Days = Mandag : " + mandag +"     Onsdag : "+sondag);
				startActivity(in);
			}
		});
		
		
	     Button btn_web = (Button) findViewById(R.id.footer_kort_btn);
	     
	     btn_web.setOnClickListener(new View.OnClickListener() {
  			@Override
  			public void onClick(View view) {
  				// Launching News Feed Screen
  				 Intent i = new Intent(LocationBased.this, MapBased.class);
  	             startActivity(i);
  			}
  		});

    }      
 }